require "path_manager/version"

module PathManager
    require 'thor'
    require 'json'
    class PathManager < Thor
        include Thor::Actions
        no_commands do
            def get_path_location
                puts File.dirname(__FILE__) + "config.json"
                file = File.read(File.dirname(__FILE__) + "/config.json")
                configs = JSON.parse(file, symbolize_names: true)
                regex = /Shell: \/bin\/([a-zA-Z\/]*)/i
                info = %x[finger `whoami`]
                shell = info.match(regex)
                shell = shell.captures.first
                paths = configs[shell.to_sym]
                paths.map! { |e| File.expand_path(e) }
                search = /^(?:export )?PATH=/
                location = {}
                catch :done do
                    paths.each_with_index do |path, index|
                        if File.exists?(path)
                            File.open(path) do |f|
                                path_found = f.each_line.detect.with_index do |line, index2|
                                    if search.match(line)
                                        location[:path] = paths[index]
                                        location[:line] = (index2 + 1)
                                        true
                                    else
                                        false
                                    end
                                end
                                throw :done if path_found
                            end
                        end
                    end
                end
                location
            end
            def add_to_path(path, shouldPrepend)
                path = path.to_s
                location = get_path_location
                File.open(location[:path], "r+") do |file|
                    while (location[:line] -= 1) > 0
                        file.readline
                    end
                    pos = file.pos
                    regex = /((?:\/|~).+)/
                    path_items = file.gets.match(regex).captures.first.split(":")
                    if path_items.last == "$PATH"
                        path_items.pop
                    end
                    if shouldPrepend
                        path_items.unshift(path)
                    else
                        path_items.push(path)
                    end
                    path_items = path_items.join(":")
                    rest = file.read
                    file.seek pos
                    file.write "export PATH=" + path_items + ":$PATH\n"
                    file.write rest
                end
            end
        end

        desc "list", "Lists the directories in your PATH variable."
        def list
            say "This is your current $PATH:"
            path_items = ENV['PATH'].split(":")
            path_items.each_with_index do |item, index|
                if index < 9
                    say "#{index+1}.  #{item}"
                else
                    say "#{index+1}. #{item}"
                end
            end
        end
        desc "prepend DIRECTORY", "Prepends the directory to your PATH variable"
        def prepend(path)
            add_to_path(path, true)
        end
        desc "append DIRECTORY", "Appends the directory to your PATH variable"
        def append(path)
            add_to_path(path, false)
        end

        desc "which PROGRAM", "Shows the the different path entry where the program appears. Like which, but not just with the first location"
        def which(program)
            program = program.to_s
            say("Warning: If you use rbenv, then the order may be incorrect for gems.", :red)
            path = ENV["PATH"]
            path = path.split(":")
            directories = []
            path.each do |dir|
                if Dir.exists?(dir)
                    entries =  Dir.entries(dir)
                    directories.push(dir.to_s + "/" + program) if entries.include?(program)
                end
            end
            directories.each_with_index do |dir, index|
                say "#{index+1}. #{dir}"
            end
        end

    end


end
